package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.common.result.Result;
import io.minio.*;
import io.minio.errors.MinioException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Tag(name = "上传管理接口")
@RestController
@RequestMapping("api/album")
//@RefreshScope
public class FileUploadApiController {

    //@Value()
    //  使用软编码读取配置文件中的地址!
    @Autowired
    private MinioConstantProperties minioConstantProperties;

   @Operation(summary = "文件上传")
    @PostMapping("/fileUpload")
    public Result fileUpload(MultipartFile file){ //文件上传的时候，前端会在页面组件封装一个name属性；这个属性是什么,MultipartFile对象就是啥
//       返回值：文件上传之后的地址url
       String url = "";
//       调用MinIO官网提供的上传API
       try {
           // Create a minioClient with the MinIO server playground, its access key and secret key.
           MinioClient minioClient =
                   MinioClient.builder() //url等不应该写死，应该使用软编码，我们给每个上传到minio的文件设置了java Bean，这里直接从java bean
//                           里面读取url、key、桶名等
                           .endpoint(minioConstantProperties.getEndpointUrl())
                           .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
                           .build();

           // Make 'asiatrip' bucket if not exist.
           boolean found =
                   minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
           if (!found) {
               // Make a new bucket called 'asiatrip'.
               minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
           } else {
               System.out.println("Bucket " + minioConstantProperties.getBucketName() + " already exists.");
           }

           //  String name = atguigu.jpg indexOf lastIndoxOf substring equals compareTo trim replaceAll split
           String myFileName = UUID.randomUUID().toString().replaceAll("-","")+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//           把文件名通过uuid添加随机编号，组成该文件的文件名
           System.out.println("fileName:\t" + myFileName);
           // Upload known sized input stream.
           minioClient.putObject( //构建者模式构建了上传文件的
                   PutObjectArgs.builder().bucket(minioConstantProperties.getBucketName()).object(myFileName).stream(
                                   file.getInputStream(), file.getSize(), -1)
                           .contentType(file.getContentType())
                           .build());
           //  返回数据url 没有赋值; 必须把上传文件拼成：url/bucketName/fileName格式，才能正确返回前端
//           endpointUrl: http://192.168.200.130:9000
           url = minioConstantProperties.getEndpointUrl()+"/"+minioConstantProperties.getBucketName()+"/"+myFileName;
           System.out.println("url:\t"+url);
       } catch (Exception e) {
           System.out.println("Error occurred: " + e);
       }
//       返回数据
       return Result.ok(url);
   }
}
